package nowcode;

public class ReverseSentenceSolution {

    public static void main(String[] args) {
        ReverseSentenceSolution solution = new ReverseSentenceSolution();
        System.out.println(solution.ReverseSentence("I am a student."));
    }

    public String ReverseSentence(String str) {

        char[] chars = str.toCharArray();

        int begin = 0;
        int index = 1;
        while (index <= chars.length) {
            if (index == chars.length || chars[index] == ' ') {
                reverse(chars, begin, index - 1);
                index++;
                begin = index;
            }
            index++;
        }
        reverse(chars, 0, chars.length - 1);
        return new String(chars);
    }

    private void reverse(char[] chars, int begin, int end) {
        while (begin < end) {
            char temp = chars[end];
            chars[end] = chars[begin];
            chars[begin] = temp;
            begin++;
            end--;
        }
    }
}
